package com.szosen.idcardActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.sam.sdticreader.WltDec;
import com.szosen.bluetooth.BluetoothListActivity;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.activity.JKDAActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.json.database.ArchiveBean;
import com.szosen.json.database.JSONDBService;
import com.szosen.util.Cache;
import com.szosen.util.ToastTool;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

@SuppressLint("NewApi")
public class IDCardActivity_bt extends BaseActivity {
    private boolean mReadIdCardFlag = false;
    BluetoothAdapter myBluetoothAdapter = null;
    BluetoothServerSocket mBThServer = null;
    BluetoothSocket mBTHSocket = null;
    InputStream mmInStream = null;
    OutputStream mmOutStream = null;
    int Readflage = -99;
    private static String btMac;
    final String usage = "请先进行蓝牙二代证配对，\r\n蓝牙默认名称：\r\n\t“Dual-SPP”，或\r\n\t起始字符为“FNY”。";
    // byte[] cmd_SAM = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
    // 0x69, 0x00, 0x03, 0x12, (byte) 0xFF, (byte) 0xEE };
    byte[] cmd_find = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
            0x69, 0x00, 0x03, 0x20, 0x01, 0x22};
    byte[] cmd_selt = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
            0x69, 0x00, 0x03, 0x20, 0x02, 0x21};
    byte[] cmd_read = {(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0x96,
            0x69, 0x00, 0x03, 0x30, 0x10, 0x23};
    byte[] recData = new byte[2500];

    IdCardMsg2 mIdCardMsg = new IdCardMsg2();
    Cache cache;
    String BLUETOOTH_NAME1 = "Dual-SPP";
    String BLUETOOTH_NAME_PREFIX1 = "FNY";
    Dialog dialog;
    UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private Context mContext;
    private static final String TAG = "BlueToolIDCard";
    private boolean mStartConnectBtDialog = false;
    private TextView tv_putIdCard;
    private boolean isNeedReadIdCard = false;

    /**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.read_id_card_new_bt);
        mContext = this;
        btconn = (Button) findViewById(R.id.btn_find_id_reader);
        btread = (Button) findViewById(R.id.btnInit);
        btclose = (Button) findViewById(R.id.btn_off);
        image = (ImageView) findViewById(R.id.ivImageview);
        txtInfo = (TextView) findViewById(R.id.tv_info);
        txtDeviceStatus = (TextView) findViewById(R.id.conn_status);
        tv_putIdCard = (TextView) findViewById(R.id.readidcard_tv_putidcard);
        // TextView tv_title = (TextView) findViewById(R.id.main_all_tv_title);
        // tv_title.setText("身份证读卡");
        // btclose.setEnabled(false);
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        txtInfo.setText(usage);
        cache = new Cache(mContext);
        image.setVisibility(View.INVISIBLE);
        txtInfo.setVisibility(View.INVISIBLE);
        mReadIdCardFlag = false;
        isNeedReadIdCard = true;
        txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
        txtDeviceStatus.setTextColor(Color.BLUE);
        if (!isConnected && !mStartConnectBtDialog) {
            new Thread() {
                public void run() {
                    System.out.println("马上开始连接。");
                    connectBTFromStatic();
                }

                ;
            }.start();
        }

        myReadIdCardThread = new Thread() {
            public void run() {
                while (isNeedReadIdCard) {
                    if (mReadIdCardFlag) {
                        readAndShowIdCard();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            ;
        };
        myReadIdCardThread.start();

        btread.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                // txtInfo.setText("");
                // txtDeviceStatus.append("");
                image.setVisibility(View.INVISIBLE);
                txtInfo.setVisibility(View.INVISIBLE);
                tv_putIdCard.setVisibility(View.VISIBLE);// 只显示放进身份证。。。
                mReadIdCardFlag = true;
                // isNeedReadIdCard=true;
            }

        });
    }

    public void connnectDeviceAgain(View view) {
        //显示正在连接。
        txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
        txtDeviceStatus.setTextColor(Color.BLUE);
        new Thread() {
            public void run() {
                connectBTFromStatic();
            }

            ;
        }.start();
    }

    public void findDevice(View view) {
        Intent serverIntent = new Intent(mContext,
                BluetoothListActivity.class);
        BluetoothListActivity.setHandler(btHandler);
        // 如果没有已经绑定的，就是为空了。那就绑定其他的了
        String s = cache.getDeviceAddress("IDCARD");
        if (TextUtils.isEmpty(s)) {
            BluetoothListActivity.setShowNoBondedDevice(true);
        }
        serverIntent.putExtra("tag", "FNY");
        startActivityForResult(serverIntent,
                BluetoothListActivity.REQUEST_CONNECT_DEVICE);
        mStartConnectBtDialog = true;
    }

    private Handler btHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothListActivity.WHAT_DISCONNECT_BT:
                    // closeBT();
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private void readAndShowIdCard() {
        int readcount = 5;
        try {
            // image.setImageBitmap(BitmapFactory.decodeResource(
            // getResources(), R.drawable.face));
            while (readcount > 1) {
                ReadCard();
                readcount = readcount - 1;
                if (Readflage > 0) {
                    readcount = 0;
                    String show = "姓名: " + mIdCardMsg.name + '\n' + "性别: "
                            + mIdCardMsg.sex + '\n' + "民族: "
                            + mIdCardMsg.nation_str + "族" + '\n' + "出生日期: "
                            + mIdCardMsg.birth_year + "-"
                            + mIdCardMsg.birth_month + "-"
                            + mIdCardMsg.birth_day + '\n' + "住址: "
                            + mIdCardMsg.address + '\n' + "身份证号码: "
                            + mIdCardMsg.id_num + '\n' + "签发机关: "
                            + mIdCardMsg.sign_office + '\n' + "有效期起始日期: "
                            + mIdCardMsg.useful_s_date_year + "-"
                            + mIdCardMsg.useful_s_date_month + "-"
                            + mIdCardMsg.useful_s_date_day + '\n';
                    if (mIdCardMsg.useful_e_date_year.equalsIgnoreCase("长") == false)
                        show = show + "有效期截止日期: "
                                + mIdCardMsg.useful_e_date_year + "-"
                                + mIdCardMsg.useful_e_date_month + "-"
                                + mIdCardMsg.useful_e_date_day + '\n';
                    else
                        show = show + "有效期截止日期: "
                                + mIdCardMsg.useful_e_date_year
                                + mIdCardMsg.useful_e_date_month;
                    myReadIdCardHandler.obtainMessage(WHAT_NAME, show)
                            .sendToTarget();
                    if (Readflage == 1) {
                        // 照片解码
                        WltDec wltdec = new WltDec();
                        try {
                            byte[] photoBmpData = wltdec
                                    .decodeToBitmap(mIdCardMsg.photo);
                            Bitmap bp = BitmapFactory.decodeByteArray(
                                    photoBmpData, 0, photoBmpData.length);
                            // 设置显示的图片
                            myReadIdCardHandler.obtainMessage(WHAT_IMAGEVIEW,
                                    bp).sendToTarget();
                            if (photoBmpData != null) {
                                Readflage = 1;// 读卡成功
                            } else {
                                Readflage = 6;// 照片解码异常
                            }
                        } catch (Exception e) {
                            Readflage = 6;// 照片解码异常
                        }
                        int n = 0;
                        int m = 0;
                        myReadIdCardHandler.obtainMessage(WHAT_SHOWDIALOG, n)
                                .sendToTarget();

                    } else {
                        // txtDeviceStatus.append("照片解码失败");
                        myReadIdCardHandler.obtainMessage(
                                WHAT_IMAGEDECODEFAILED).sendToTarget();
                    }
                } else {
                    /*
					 * if (Readflage == -2) { txtDeviceStatus.setText("蓝牙连接异常");
					 * } if (Readflage == -3) {
					 * txtDeviceStatus.setText("无卡或卡片已读过"); } if (Readflage ==
					 * -4) { txtDeviceStatus.setText("无卡或卡片已读过"); } if
					 * (Readflage == -5) { txtDeviceStatus.setText("读卡失败"); } if
					 * (Readflage == -99) { txtDeviceStatus.setText("操作异常"); }
					 */
                    myReadIdCardHandler.obtainMessage(WHAT_READIDCARDFAILED,
                            Readflage).sendToTarget();
                }
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            // txtDeviceStatus.setText("读取数据异常！");
            myReadIdCardHandler.obtainMessage(WHAT_READIDCARDERROR)
                    .sendToTarget();
        }
    }

    /***
     * 关闭蓝牙通道。
     */
    private void closeBT() {
        try {
            // if ((mmInStream == null) || (mmOutStream == null)) {
            // return;
            // }
            if (mBTHSocket != null) {
                // 不为空，就获取输入输出流，
                mBTHSocket.close();
//				mmOutStream = mBTHSocket.getOutputStream();
//				mmInStream = mBTHSocket.getInputStream();
//				System.out.println("mBTHSocket.close()关闭");
            }
            if (mBThServer != null) {
//				System.out.println("mBThServer.close()关闭");
                mBThServer.close();
            }
            if (mmOutStream != null) {
                mmOutStream.close();
//				System.out.println("mmOutStream.close()关闭");
            }
            if (mmInStream != null) {
                mmInStream.close();
//				System.out.println("mmInStream.close()关闭");
            }
            System.out.println("mbthsocket==null" + (mBTHSocket == null)
                    + "server==null" + (mBThServer == null));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isConnected = false;// 蓝牙是否已经连接。如果已经连接，在onResume就不连接了。

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onResume() {
        super.onResume();
        mStartConnectBtDialog = false;
        TextView tv_service_state = (TextView) findViewById(R.id.tv_server_state);
        super.setTitleContent("【身份证刷卡】");
        String s = cache.getDeviceAddress("IDCARD");
        if (TextUtils.isEmpty(s)) {
            txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NOBOND);
            txtDeviceStatus.setTextColor(Color.RED);
        }
    }

    @Override
    public void onBackPressed() {
        // 尿液
        String connectStatus = txtDeviceStatus.getText().toString();
        if (connectStatus.equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
            ToastTool.showLong(context, "正在连接设备，请勿退出!");
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 查找蓝牙后，用户指定连接设备，返回进行连接
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case BluetoothListActivity.REQUEST_CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) {
                    btMac = data.getExtras().getString(
                            BluetoothListActivity.EXTRA_DEVICE_ADDRESS);
                    Log.i("address", btMac);
                    txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
                    txtDeviceStatus.setTextColor(Color.BLUE);
                    BluetoothDevice btDev = myBluetoothAdapter
                            .getRemoteDevice(btMac);
                    connectDevice(btDev);
                }
                break;
        }
    }

    // 自动连接蓝牙功能。
    private void connectBTFromStatic() {
        btMac = cache.getDeviceAddress("IDCARD");
        if (TextUtils.isEmpty(btMac)) {
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTHAND).sendToTarget();
            btconn.setEnabled(true);
            return;
        }
        BluetoothDevice btDev = myBluetoothAdapter.getRemoteDevice(btMac);
        connectDevice(btDev);
        System.out.println("正在自动连接蓝牙设备！！！");
    }

    private Button btconn;
    private Button btread;
    private ImageView image;
    private Button btclose;
    private TextView txtDeviceStatus;// 读卡器连接状态
    private TextView txtInfo;

    private boolean connectDevice(BluetoothDevice device) {
        try {
            if (!myBluetoothAdapter.isEnabled()) {
                myBluetoothAdapter.enable();
            }
            // Intent discoverableIntent = new Intent(
            // BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//
            // 使得蓝牙处于可发现模式，持续时间150s
            // discoverableIntent.putExtra(
            // BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
            // mBTHSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            // int sdk = Integer.parseInt(Build.VERSION.SDK);
            // if (sdk >= 10) {
            // mBTHSocket = device
            // .createInsecureRfcommSocketToServiceRecord(MY_UUID);
            // } else {
            // mBTHSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            // }
            // myBluetoothAdapter.cancelDiscovery();
            // 原来的连接方式
            mBTHSocket = device
                    .createInsecureRfcommSocketToServiceRecord(MY_UUID);
            mBThServer = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(
                    "myServerSocket", MY_UUID);
            mBTHSocket.connect();
            mmInStream = mBTHSocket.getInputStream();
            mmOutStream = mBTHSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR).sendToTarget();
            return false;
        }
        if ((mmInStream != null) && (mmInStream != null)) {
            // 发送连接成功的handler
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTSUCCESS)
                    .sendToTarget();
            // 保存连接的蓝牙地址
            cache.saveDeviceAddress("IDCARD", device.getAddress());
            Log.d("WELLCOM", "success");
            return true;
        } else {
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR).sendToTarget();
            return false;
        }
    }

    private final static int WHAT_IMAGEVIEW = 111;
    private final static int WHAT_NAME = 222;
    private final static int WHAT_IMAGEDECODEFAILED = 444;
    private final static int WHAT_SHOWDIALOG = 666;
    private final static int WHAT_READIDCARDFAILED = 999;
    private final static int WHAT_READIDCARDERROR = 99999;
    private final static int WHAT_CONNECTERROR = 44444;
    private final static int WHAT_CONNECTSUCCESS = 66666;
    private final static int WHAT_CONNECTHAND = 55555;

    @SuppressWarnings("deprecation")
    @Override
    protected void onDestroy() {
        isNeedReadIdCard = false;
        super.onDestroy();
        try {
            isNeedReadIdCard = false;
            // myReadIdCardThread.stop();
            myReadIdCardThread.interrupt();
            closeBT();
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED)
        // {
        // // 不显示其他内容。
        // BluetoothListActivity.setShowNoBondedDevice(false);
        // // bluetoothService.close();
        // }
    }

    Handler myReadIdCardHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_IMAGEVIEW:
                    // 读取到身份证图片
                    image.setVisibility(View.VISIBLE);
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    Bitmap bmp = (Bitmap) msg.obj;
                    image.setImageBitmap(bmp);
                    break;
                case WHAT_NAME:
                    // 读取到身份证名字
                    // tv.setVisibility(View.VISIBLE);
                    txtInfo.setVisibility(View.VISIBLE);
                    mReadIdCardFlag = false;
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    String s = (String) msg.obj;
                    txtInfo.setText("您好, " + s);
                    boolean flag = false;
                    JSONDBService dService = JSONDBService.getInstance(context);
                    List<Object> list = dService.getAll(new ArchiveBean());
                    for (int i = 0; list != null && i < list.size(); i++) {
                        ArchiveBean hr = (ArchiveBean) list.get(i);
                        String card = hr.getIdcard().trim();
                        if (!TextUtils.isEmpty(card)
                                && card.equals(mIdCardMsg.id_num)) {
                            Intent intent = new Intent();
                            intent.putExtra("IdCard", mIdCardMsg.id_num);
                            intent.putExtra("name", mIdCardMsg.name);
                            setResult(0, intent);
                            flag = true;
                            isNeedReadIdCard = false;
                            closeBT();
                            finish();
                            return;
                        }
                    }
                    if (!flag) {
                        Intent intent = new Intent(IDCardActivity_bt.this,
                                JKDAActivity.class);
                        intent.putExtra("flag", "addUser");
                        intent.putExtra("idCard", mIdCardMsg.id_num);
                        intent.putExtra("name", mIdCardMsg.name);
                        intent.putExtra("address", mIdCardMsg.address);
                        intent.putExtra("sex", mIdCardMsg.sex);
//                        intent.putExtra("nation", mIdCardMsg.nation_str);
//                        startActivity(intent);
                        isNeedReadIdCard = false;
                        closeBT();
                        finish();
                    }
                    break;
                case WHAT_IMAGEDECODEFAILED:
                    ToastTool.showShort(
                            mContext,
                            "照片解码失败，请检查路径"
                                    + Environment.getExternalStorageDirectory()
                                    + "/wltlib/");
                    image.setImageBitmap(BitmapFactory.decodeResource(
                            getResources(), R.drawable.face));
                    image.setVisibility(View.INVISIBLE);
                    // tv.setVisibility(View.INVISIBLE);
                    break;
                case WHAT_CONNECTHAND:
                    image.setVisibility(View.INVISIBLE);
                    txtInfo.setVisibility(View.INVISIBLE);
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    ToastTool.showLongClear(mContext, "设备自动连接失败，请手动连接设备！");
                    break;
                case WHAT_SHOWDIALOG:
                    // mReadIdCardFlag = false;
                    tv_putIdCard.setVisibility(View.INVISIBLE);
                    break;
                case WHAT_READIDCARDFAILED:
                    tv_putIdCard.setVisibility(View.VISIBLE);
                    int Readflage = (int) msg.obj;
                    String showMessage = "";
                    if (Readflage == -2) {
                        // showMessage="蓝牙连接异常";
                    }
                    if (Readflage == -4) {
                        showMessage = "无卡或卡片已读过";
                    }
                    if (Readflage == -5) {
                        showMessage = "读卡失败";
                    }
                    if (Readflage == -99) {
                        // showMessage="操作异常";
                        myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR)
                                .sendToTarget();
                    }
                    if (!TextUtils.isEmpty(showMessage)) {
                        ToastTool.showShort(mContext, showMessage);
                    }
                    break;
                case WHAT_READIDCARDERROR:
                    // ToastTool.showShort(mContext, "");
                    txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NULL);
                    txtDeviceStatus.setTextColor(Color.RED);
                    break;
                case WHAT_CONNECTSUCCESS:
                    tv_putIdCard.setVisibility(View.VISIBLE);// 设备连接成功后显示放进身份证。。。
                    txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS);
                    txtDeviceStatus.setTextColor(Color.BLUE);
                    mReadIdCardFlag = true;
                    break;
                case WHAT_CONNECTERROR:
                    // ToastTool.showShort(mContext, "设备连接失败");
                    txtDeviceStatus.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                    txtDeviceStatus.setTextColor(Color.RED);
                    break;
                default:
                    break;
            }
        }

        ;
    };
    private Thread myReadIdCardThread;

    private void ReadCard() {
        try {
            System.out.println("身份证正在读取");
            if ((mmInStream == null) || (mmInStream == null)) {
                Readflage = -2;// 连接异常
                myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR)
                        .sendToTarget();
                return;
            }
            mmOutStream.write(cmd_find);
            Thread.sleep(200);
            int datalen = mmInStream.read(recData);
            if (recData[9] == -97) {
                mmOutStream.write(cmd_selt);
                Thread.sleep(200);
                datalen = mmInStream.read(recData);
                if (recData[9] == -112) {
                    mmOutStream.write(cmd_read);
                    Thread.sleep(1000);
                    byte[] tempData = new byte[2500];
                    if (mmInStream.available() > 0) {
                        datalen = mmInStream.read(tempData);
                    } else {
                        Thread.sleep(500);
                        if (mmInStream.available() > 0) {
                            datalen = mmInStream.read(tempData);
                        }
                    }
                    int flag = 0;
                    if (datalen < 1296) {
                        for (int i = 0; i < datalen; i++, flag++) {
                            recData[flag] = tempData[i];
                        }
                        Thread.sleep(1000);
                        if (mmInStream.available() > 0) {
                            datalen = mmInStream.read(tempData);
                        } else {
                            Thread.sleep(500);
                            if (mmInStream.available() > 0) {
                                datalen = mmInStream.read(tempData);
                            }
                        }
                        for (int i = 0; i < datalen; i++, flag++) {
                            recData[flag] = tempData[i];
                        }
                    } else {
                        for (int i = 0; i < datalen; i++, flag++) {
                            recData[flag] = tempData[i];
                        }
                    }
                    tempData = null;
                    if (flag >= 1297) {
                        if (recData[9] == -112) {

                            byte[] dataBuf = new byte[256];
                            for (int i = 0; i < 256; i++) {
                                dataBuf[i] = recData[16 + i];
                            }

                            try {
                                char[] pucCHMsgStr = new char[128];
                                DecodeByte(dataBuf, pucCHMsgStr);// 将读取的身份证中的信息字节，解码成可阅读的文字
                                PareseItem(pucCHMsgStr, mIdCardMsg); // 将信息解析到msg中

                                Log.i("WELLCOM", String.valueOf(pucCHMsgStr));
                                byte[] wltdata = new byte[1024];
                                for (int i = 0; i < 1024; i++) {
                                    wltdata[i] = recData[16 + 256 + i];
                                }
                                mIdCardMsg.photo = wltdata;

                                Log.i("WELLCOM", String.valueOf(pucCHMsgStr));
                                Readflage = 1;// 读卡成功
                                Log.i("WELLCOM", String.valueOf(pucCHMsgStr));

                            } catch (Exception e) {
                                Readflage = -5;// 读卡失败！
                                e.printStackTrace();
                            }
                        } else {
                            Readflage = -5;// 读卡失败！
                        }
                    } else {
                        Readflage = -5;// 读卡失败
                    }
                } else {
                    Readflage = -4;// 选卡失败
                }
            } else {
                Readflage = -3;// 寻卡失败
            }

        } catch (IOException e) {
            Readflage = -99;// 读取数据异常
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR).sendToTarget();
        } catch (InterruptedException e) {
            Readflage = -99;// 读取数据异常
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR).sendToTarget();
        }
        if (Readflage == -99) {
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTERROR).sendToTarget();
        } else {
            myReadIdCardHandler.obtainMessage(WHAT_CONNECTSUCCESS)
                    .sendToTarget();
        }
        Log.i("WELLCOM", "Readflage=" + Readflage);
    }

    private String decodeNation(int code) {
        String nation;
        switch (code) {
            case 1:
                nation = "汉";
                break;
            case 2:
                nation = "蒙古";
                break;
            case 3:
                nation = "回";
                break;
            case 4:
                nation = "藏";
                break;
            case 5:
                nation = "维吾尔";
                break;
            case 6:
                nation = "苗";
                break;
            case 7:
                nation = "彝";
                break;
            case 8:
                nation = "壮";
                break;
            case 9:
                nation = "布依";
                break;
            case 10:
                nation = "朝鲜";
                break;
            case 11:
                nation = "满";
                break;
            case 12:
                nation = "侗";
                break;
            case 13:
                nation = "瑶";
                break;
            case 14:
                nation = "白";
                break;
            case 15:
                nation = "土家";
                break;
            case 16:
                nation = "哈尼";
                break;
            case 17:
                nation = "哈萨克";
                break;
            case 18:
                nation = "傣";
                break;
            case 19:
                nation = "黎";
                break;
            case 20:
                nation = "傈僳";
                break;
            case 21:
                nation = "佤";
                break;
            case 22:
                nation = "畲";
                break;
            case 23:
                nation = "高山";
                break;
            case 24:
                nation = "拉祜";
                break;
            case 25:
                nation = "水";
                break;
            case 26:
                nation = "东乡";
                break;
            case 27:
                nation = "纳西";
                break;
            case 28:
                nation = "景颇";
                break;
            case 29:
                nation = "柯尔克孜";
                break;
            case 30:
                nation = "土";
                break;
            case 31:
                nation = "达斡尔";
                break;
            case 32:
                nation = "仫佬";
                break;
            case 33:
                nation = "羌";
                break;
            case 34:
                nation = "布朗";
                break;
            case 35:
                nation = "撒拉";
                break;
            case 36:
                nation = "毛南";
                break;
            case 37:
                nation = "仡佬";
                break;
            case 38:
                nation = "锡伯";
                break;
            case 39:
                nation = "阿昌";
                break;
            case 40:
                nation = "普米";
                break;
            case 41:
                nation = "塔吉克";
                break;
            case 42:
                nation = "怒";
                break;
            case 43:
                nation = "乌孜别克";
                break;
            case 44:
                nation = "俄罗斯";
                break;
            case 45:
                nation = "鄂温克";
                break;
            case 46:
                nation = "德昂";
                break;
            case 47:
                nation = "保安";
                break;
            case 48:
                nation = "裕固";
                break;
            case 49:
                nation = "京";
                break;
            case 50:
                nation = "塔塔尔";
                break;
            case 51:
                nation = "独龙";
                break;
            case 52:
                nation = "鄂伦春";
                break;
            case 53:
                nation = "赫哲";
                break;
            case 54:
                nation = "门巴";
                break;
            case 55:
                nation = "珞巴";
                break;
            case 56:
                nation = "基诺";
                break;
            case 97:
                nation = "其他";
                break;
            case 98:
                nation = "外国血统中国籍人士";
                break;
            default:
                nation = "";
                break;
        }
        return nation;
    }

    // 字节解码函数
    void DecodeByte(byte[] msg, char[] msg_str) throws Exception {
        byte[] newmsg = new byte[msg.length + 2];

        newmsg[0] = (byte) 0xff;
        newmsg[1] = (byte) 0xfe;

        for (int i = 0; i < msg.length; i++)
            newmsg[i + 2] = msg[i];

        String s = new String(newmsg, "UTF-16");
        for (int i = 0; i < s.toCharArray().length; i++)
            msg_str[i] = s.toCharArray()[i];
    }

    // 分段信息提取
    void PareseItem(char[] pucCHMsgStr, IdCardMsg2 msg) {
        msg.name = String.copyValueOf(pucCHMsgStr, 0, 15);
        String sex_code = String.copyValueOf(pucCHMsgStr, 15, 1);

        if (sex_code.equals("1"))
            msg.sex = "男";
        else if (sex_code.equals("2"))
            msg.sex = "女";
        else if (sex_code.equals("0"))
            msg.sex = "未知";
        else if (sex_code.equals("9"))
            msg.sex = "未说明";

        String nation_code = String.copyValueOf(pucCHMsgStr, 16, 2);
        try {
            int code = Integer.valueOf(nation_code);
            msg.nation_str = decodeNation(code);
        } catch (Exception e) {
            msg.nation_str = "";
        }

        msg.birth_year = String.copyValueOf(pucCHMsgStr, 18, 4);
        msg.birth_month = String.copyValueOf(pucCHMsgStr, 22, 2);
        msg.birth_day = String.copyValueOf(pucCHMsgStr, 24, 2);
        msg.address = String.copyValueOf(pucCHMsgStr, 26, 35);
        msg.id_num = String.copyValueOf(pucCHMsgStr, 61, 18);
        msg.sign_office = String.copyValueOf(pucCHMsgStr, 79, 15);

        msg.useful_s_date_year = String.copyValueOf(pucCHMsgStr, 94, 4);
        msg.useful_s_date_month = String.copyValueOf(pucCHMsgStr, 98, 2);
        msg.useful_s_date_day = String.copyValueOf(pucCHMsgStr, 100, 2);

        msg.useful_e_date_year = String.copyValueOf(pucCHMsgStr, 102, 4);
        msg.useful_e_date_month = String.copyValueOf(pucCHMsgStr, 106, 2);
        if (msg.useful_e_date_year.equalsIgnoreCase("长"))
            msg.useful_e_date_day = "";
        else
            msg.useful_e_date_day = String.copyValueOf(pucCHMsgStr, 108, 2);
    }

    Bitmap bmp(Bitmap bp) {
        float scaleWidth = 1;
        float scaleHeight = 1;
        int bmpWidth = bp.getWidth();
        int bmpHeight = bp.getHeight();
		/* 设置图片放大的比例 */
        double scale = 2;
		/* 计算这次要放大的比例 */
        scaleWidth = (float) (scaleWidth * scale);
        scaleHeight = (float) (scaleHeight * scale);

		/* 产生reSize后的Bitmap对象 */
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizeBmp = Bitmap.createBitmap(bp, 0, 0, bmpWidth, bmpHeight,
                matrix, true);
        return resizeBmp;
    }

}

class IdCardMsg2 {
    public String name;
    public String sex;
    public String nation_str;

    public String birth_year;
    public String birth_month;
    public String birth_day;
    public String address;
    public String id_num;
    public String sign_office;

    public String useful_s_date_year;
    public String useful_s_date_month;
    public String useful_s_date_day;

    public String useful_e_date_year;
    public String useful_e_date_month;
    public String useful_e_date_day;
    public byte[] photo;

}